<?php

namespace App\Http\Controllers;

require_once app_path('Libs') . '/../../vendor/alipay_app/wappay/service/AlipayTradeService.php';
use App\Models\CompanyJob;
use App\Models\Interview;
use App\Models\PersonalUser;
use App\Models\Product;
use App\Models\ProductList;
use App\Models\ProductOrder;
use App\Models\Resume;
use App\Models\ResumeSend;
use DB;
use AlipayTradeService;
use Illuminate\Database\QueryException;

/**
 * 微信授权相关接口
 *
 * @link http://www.phpddt.com
 */
class PaymentController extends Controller
{
    /**
     * 微信支付
     * @param $data
     * @param $type 1为小程序，2为公众号，3为APP
     * @return array|mixed
     */
    public function wx_pay($odata)
    {
        $wxApp = config('pay.wechat_app');
        $wxAccount = config('pay.wechat_account');
        $wxMerchant = config('pay.wechat_merchant');
        $wxInfo = config('pay.wechat_info');
        $wxConfig = array_merge($wxAccount, $wxMerchant, $wxInfo);
        $key = $wxConfig['key'];

        //APP
        $odata['appid'] = $wxApp['appid'];
        $odata["trade_type"] = 'APP';

        $postarray = [
            "appid" => $odata['appid'],
            "body" => $odata['body'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "out_trade_no" => $odata['out_trade_no'],
            "spbill_create_ip" => $odata['client_ip'],
            "total_fee" => $odata['money'] * 100,
//            "total_fee" => 1,
//            'profit_sharing' => 'Y',
            "trade_type" => $odata['trade_type']
        ];

        $postarray["notify_url"] = $wxConfig['notify_url_shop'];
        $postarray['scene_info'] = isset($odata['scene_info']) ? $odata['scene_info'] : '';
        $postarray = array_filter($postarray);

        $postarray['sign'] = $this->mkSign($postarray, $key);
        $postdata = self::arraytoxml($postarray);

        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $data = $this->sendData($url, $postdata);
//        file_put_contents("log11111.txt", $postdata, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($result['return_code'] == 'FAIL') {
            return ['status' => 0, 'msg' => $result['return_msg']];
        }
        if ($result['result_code'] == 'FAIL') {
            return ['status' => 0, 'msg' => $result['err_code_des']];
        }

        //APP支付
        $ndata = [
            "appid" => $result['appid'],
            "partnerid" => $result['mch_id'],
            "prepayid" => $result['prepay_id'],
            "package" => "Sign=WXPay",
            "noncestr" => $result['nonce_str'],
            "timestamp" => time()
        ];

        $ndata["sign"] = $this->mkSign($ndata, $key);

//        file_put_contents("log111.txt", json_encode($ndata), FILE_APPEND);

        return ['status' => 4, 'data' => json_encode($ndata)];
    }

    /**
     * 微信支付到银行卡
     * @return array
     */
    public function payBank($data)
    {
        $wxAccount = config('pay.wechat_account');
        $wxMerchant = config('pay.wechat_merchant');
        $wxInfo = config('pay.wechat_info');

        $wxConfig = array_merge($wxAccount, $wxMerchant, $wxInfo);
        $key = $wxConfig['key'];

        $rsa = new RSAController(file_get_contents('wx_cert/new_pub_key.pem'), '');
        $odata = [
            //商户号
            "mch_id" => $wxConfig['mch_id'],
            //商户订单号
            "partner_trade_no" => md5(time()),
            //随机字符串
            "nonce_str" => md5(time()),
            //收款方银行卡号
            "enc_bank_no" => $rsa->public_encrypt($data['bank_no']),
            //收款方用户名
            "enc_true_name" => $rsa->public_encrypt($data['true_name']),
            //收款方开户行
            "bank_code" => $data['bank_code'],
            //付款金额
            "amount" => $data['money'] * 100,
            //付款说明
            "desc" => "账户提现",
        ];


        //微信签名
        $odata["sign"] = $this->mkSign($odata, $key);
        //以XML的格式POST到服务器
        $postdata = self::arraytoxml($odata);
        //POST到微信服务器的网址
        $url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";

        //以XML的格式POST到服务器
        $ndata = self::postXmlCurl($wxInfo, $postdata, $url, true);

        file_put_contents("logwd.txt", $ndata, FILE_APPEND);
        //POST获取到的内容转成对象
        $result = json_decode(json_encode(simplexml_load_string($ndata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($result['return_code'] == 'FAIL') {
            return ['status' => 0, 'msg' => $result['return_msg']];
        }
        if ($result['result_code'] == 'FAIL') {
            return ['status' => 0, 'msg' => $result['err_code_des']];
        }

        return $result;
    }

    /**
     * 添加分账接收方
     * @param $openid
     * @return array
     */
    public function addReceiver($receiver)
    {
        $wxConfig = config('wechat_account');
        $wechat_applet = config('wechat_applet');

        $postarray = [
            "appid" => $wxConfig['app_id'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "sign_type" => 'HMAC-SHA256',
            'receiver' => $receiver
        ];

        $key = $wechat_applet['key'];
        $postarray['sign'] = $this->mkSign($postarray, $key, 'HMAC-SHA256');

        $postarray['receiver'] = json_encode($postarray['receiver']);
        $postdata = self::arraytoxml($postarray);
        $url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        $data = $this->sendData($url, $postdata);
        file_put_contents("log11111.txt", $data, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $result;
    }

    /**
     * 删除分账用户
     * @param $receiver
     * @return mixed
     */
    public function delReceiver($receiver)
    {
        $wxConfig = config('wechat_account');
        $wechat_applet = config('wechat_applet');

        $postarray = [
            "appid" => $wxConfig['app_id'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "sign_type" => 'HMAC-SHA256',
            'receiver' => $receiver
        ];

        $key = $wechat_applet['key'];
        $postarray['sign'] = $this->mkSign($postarray, $key, 'HMAC-SHA256');

        $postarray['receiver'] = json_encode($postarray['receiver']);
        $postdata = self::arraytoxml($postarray);
        $url = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
        $data = $this->sendData($url, $postdata);
        file_put_contents("log1111.txt", $data, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $result;
    }

    /**
     * 开始分账
     * @param $receivers
     * @param $orderNo
     * @param $transactionId
     * @return mixed
     */
    public function sendAccount($receivers, $orderNo, $transactionId)
    {
        $wxConfig = config('wechat_account');

        $postarray = array(
            "appid" => $wxConfig['app_id'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "out_order_no" => $orderNo,
            'transaction_id' => $transactionId,
            "sign_type" => 'HMAC-SHA256',
            'receivers' => $receivers
        );

        $wechat_applet = config('wechat_applet');
        $key = $wechat_applet['key'];

        $postarray['sign'] = $this->mkSign($postarray, $key, 'HMAC-SHA256');
        $postarray['receivers'] = json_encode($postarray['receivers']);

        $postdata = self::arraytoxml($postarray);
        $url = "https://api.mch.weixin.qq.com/secapi/pay/multiprofitsharing";
        $data = self::postXmlCurl($wxConfig, $postdata, $url, true);
        file_put_contents("log111.txt", $data, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $result;
    }

    /**
     * 分账完结
     * @param $orderNo
     * @param $transactionId
     * @return mixed
     */
    public function finishAccount($orderNo, $transactionId)
    {
        $wxConfig = config('wechat_account');

        $postarray = array(
            "appid" => $wxConfig['app_id'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "out_order_no" => $orderNo,
            'transaction_id' => $transactionId,
            "sign_type" => 'HMAC-SHA256',
            'description' => '分账已完成'
        );

        $wechat_applet = config('wechat_applet');
        $key = $wechat_applet['key'];

        $postarray['sign'] = $this->mkSign($postarray, $key, 'HMAC-SHA256');

        $postdata = self::arraytoxml($postarray);
        $url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish";
        $data = self::postXmlCurl($wxConfig, $postdata, $url, true);
        file_put_contents("log11.txt", $data, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $result;
    }

    /**
     * 查询分账结果
     * @param $orderNo
     * @param $transactionId
     * @return mixed
     */
    public function accountResults($orderNo, $transactionId)
    {
        $wxConfig = config('wechat_account');

        $postarray = array(
//            "appid" => $wxConfig['app_id'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "out_order_no" => $orderNo,
            'transaction_id' => $transactionId,
            "sign_type" => 'HMAC-SHA256',
        );

        $wechat_applet = config('wechat_applet');
        $key = $wechat_applet['key'];

        $postarray['sign'] = $this->mkSign($postarray, $key, 'HMAC-SHA256');

        $postdata = self::arraytoxml($postarray);
        $url = "https://api.mch.weixin.qq.com/secapi/pay/profitsharingquery";
        $data = self::postXmlCurl($wxConfig, $postdata, $url, true);
        file_put_contents("log1.txt", $data, FILE_APPEND);
        $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $result;
    }

    /**
     *
     * @param $order_num
     * @param $type
     * @return array
     */
    function checkOrderByNum($order_num, $type)
    {
        $wxConfig = config('wechat_account');
        switch ($type) {
            case 1:
                //小程序
                $wechat_applet = config('wechat_applet');
                $wxConfig['appid'] = $wechat_applet['app_id'];
                $wxConfig['trade_type'] = 'JSAPI';
                $key = $wechat_applet['key'];
                break;
            case 2:
                //微信公众号
                break;
            case 3:
                //APP
                break;
        }

        $data = array(
            "appid" => $wxConfig['appid'],
            "mch_id" => $wxConfig['mch_id'],
            "nonce_str" => $wxConfig['noncestr'],
            "out_trade_no" => $order_num,
        );

        $data['sign'] = $this->mkSign($data, $key);
        $postdata = self::arraytoxml($data);
        $url = "https://api.mch.weixin.qq.com/pay/orderquery";
        $result = $this->sendData($url, $postdata);//得到的xml格式
        //xml格式转化为数组
        $result = json_decode(json_encode(simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }


    /**
     * 生成签名
     * @param $postarray
     * @param $appKey
     * @param string $signType
     * @return string
     */
    function mkSign($postarray, $appKey, $signType = 'MD5')
    {
        ksort($postarray);
        $poststr = '';
        foreach ($postarray as $p => $v) {
            if ($poststr) {
                if (is_array($v)) {
                    $poststr .= '&' . $p . '=' . json_encode($v);
                } else {
                    $poststr .= '&' . $p . '=' . $v;
                }
            } else {
                $poststr .= $p . '=' . $v;
            }
        }
        $poststr .= '&key=' . $appKey;
        file_put_contents("log11111.txt", $poststr, FILE_APPEND);
        if ($signType == 'MD5') {
            $sign = strtoupper(md5($poststr));
        } elseif ($signType == 'HMAC-SHA256') {
            $sign = strtoupper(hash_hmac("sha256", $poststr, $appKey));
        }

        return $sign;
    }

    /**
     * 获取prepareid
     * @param $data
     * @return mixed
     */
    function getPrepayId($data)
    {
        $ob = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $res = json_decode(json_encode($ob), true);
        return $res['prepay_id'];
    }

    /*
     * 发送数据
     */
    function sendData($url, $post_data)
    {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式

        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;

    }

    /**
     * 数组转化为xml
     * @param $postarray
     * @return string
     */
    function arraytoxml($postarray)
    {
        $postdata = '<xml>';
        foreach ($postarray as $p => $v) {
            $postdata .= '<' . $p . '>' . $v . '</' . $p . '>';
        }
        $postdata .= '</xml>';

        return $postdata;
    }

    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param WxPayConfigInterface $config 配置对象
     * @param string $xml 需要post的xml数据
     * @param string $url url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second url执行超时时间，默认30s
     * @throws WxPayException
     */
    private static function postXmlCurl($config, $xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

//        $proxyHost = "0.0.0.0";
//        $proxyPort = 0;
//        $config->GetProxy($proxyHost, $proxyPort);
        //如果有配置代理这里就设置代理
//        if($proxyHost != "0.0.0.0" && $proxyPort != 0){
//            curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
//            curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
//        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//严格校验
//        curl_setopt($ch,CURLOPT_USERAGENT, $ua);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if ($useCert == true) {
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            //证书文件请放入服务器的非web目录下
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, $config['apiclient_cert']);
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, $config['apiclient_key']);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
        }
    }

    /**
     * 微信支付回调
     * @return string
     */
    public function wxNotifyJob()
    {
        //获取返回的xml数据
//        $notify = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify = file_get_contents("php://input");
        file_put_contents("log1.txt",$notify,FILE_APPEND);
        //奖xml数据转换成数组
        $result = json_decode(json_encode(simplexml_load_string($notify, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        //签名验证
//        $result_sign = $result['sign'];
//        unset($result['sign']);
//
//        $payment = new PaymentController();
//        $key = config('pay.wechat_info.key');
//        $sign = $payment->mkSign($result, $key);
//        file_put_contents("log11.txt", $result_sign . '-' . $sign . '-' . $result['return_code'] . '-' . $result['result_code']);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            //执行逻辑
            $orderNum = substr($result['out_trade_no'], 1);
            file_put_contents("log2.txt",$orderNum);
            $this->handleJob($orderNum);
            $result = true;
        } else {
            $result = false;
        }
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }

        echo $str;
        return $str;
    }

    /**
     * 支付宝回调
     * @return bool
     */
    public function alipayNotifyJob()
    {
        $arr = $_POST;
        $config = config('pay.ali_pay');
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST, true));
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if ($result) {//验证成功

            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];

            if ($trade_status == 'TRADE_FINISHED') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if ($trade_status == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            $this->handleJob($out_trade_no);
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            echo "success";        //请不要修改或删除

        } else {
            //验证失败
            echo "fail";    //请不要修改或删除

        }
    }

    /**
     * 支付处理
     * @param $orderNum
     */
    public function handleJob($orderNum)
    {
        $jobInfo = CompanyJob::where('order_num', $orderNum)->first();
        if ($jobInfo->job_status == 10) {
            CompanyJob::where('order_num', $orderNum)->update(['job_status' => 20]);
        }

        $time = date('Y-m-d H:i:s');
        $personnelUid1 = ResumeSend::where('job_id', $jobInfo->id)->value('personal_uid');
        $personnelUid2 = Interview::where('job_id', $jobInfo->id)->value('personal_uid');

        $personnelUid = $personnelUid1 > 0 ? $personnelUid1 : ($personnelUid2 > 0 ? $personnelUid2 : 0);

        $mobile = PersonalUser::where('uid', $personnelUid)->value('mobile');

        if ($mobile) {
            $realname = Resume::where('uid', $personnelUid)->value('realname');
            $content = "尊敬的{$realname}：您好！您申请的职位所属企业已于{$time}预支付佣金，快去网站与他联系吧！【廉德劳务】";
            $sms = new SmsController();
            $sms->sendMsg($mobile, urlencode($content));
        }
    }

    /**
     * 微信支付回调
     * @return string
     */
    public function wxNotifyShop()
    {
        //获取返回的xml数据
//        $notify = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify = file_get_contents("php://input");
        //奖xml数据转换成数组
        $result = json_decode(json_encode(simplexml_load_string($notify, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        //签名验证
//        $result_sign = $result['sign'];
//        unset($result['sign']);
//
//        $payment = new PaymentController();
//        $key = config('pay.wechat_info.key');
//        $sign = $payment->mkSign($result, $key);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            //执行逻辑
            $orderNum = $result['out_trade_no'];
            $this->handleShop($orderNum);
            $result = true;
        } else {
            $result = false;
        }
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }

        echo $str;
        return $str;
    }

    /**
     * 支付宝回调
     * @return bool
     */
    public function alipayNotifyShop()
    {
        $arr = $_POST;
        $config = config('pay.ali_pay');
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST, true));
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if ($result) {//验证成功

            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            //交易状态
            $trade_status = $_POST['trade_status'];

            if ($trade_status == 'TRADE_FINISHED') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if ($trade_status == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            $this->handleShop($out_trade_no);
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            echo "success";        //请不要修改或删除

        } else {
            //验证失败
            echo "fail";    //请不要修改或删除

        }
    }

    /**
     * 支付处理
     * @param $orderNum
     */
    public function handleShop($orderNum)
    {
        $data = ['pay_time' => time(), 'status' => 1];
        DB::beginTransaction();
        try {
            ProductOrder::where('order_number', $orderNum)->update($data);
            ProductList::where('order_numbero', $orderNum)->update($data);

            $list = ProductList::where('order_numbero', $orderNum)->select('product_id', 'num')->get();
            foreach ($list as $v) {
                Product::where('id', $v->product_id)->increment('sell_num', $v->num);
//                Product::where('id', $v->product_id)->decrement('num', $v->num);
            }
            DB::commit();
        } catch (QueryException $exception) {
            DB::rollback();
        }
    }
}
